package com.zl.basis.tip;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;

/**
 * Created by panes on 2018/4/10.
 */

public class SoundUtil {
    private static final int DEF_COOL_TIME = 2 * 1000;
    private static SoundPool soundPool;
    private static long lastPlayTime = -1;
    private static long lastCoolTime = 0;

    public static SoundPool getSoundPool() {
        if (null == soundPool) {
            synchronized (SoundUtil.class) {
                if (null == soundPool) {
                    SoundPool.Builder builder = new SoundPool.Builder();
                    //传入音频的数量
                    builder.setMaxStreams(1);
                    //AudioAttributes是一个封装音频各种属性的类
                    AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
                    //设置音频流的合适属性
                    attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
                    builder.setAudioAttributes(attrBuilder.build());
                    soundPool = builder.build();
                }
            }
        }
        return soundPool;
    }

    public static void init() {
        getSoundPool();
    }

    /**
     * 适合播放声音短，文件小
     * 可以同时播放多种音频
     * 消耗资源较小
     */
    public static synchronized void playSound(Context mContext, int rawId, int volume, int spaceTime) {
        if (rawId == 0 || null == mContext) {
            return;
        }
        if (lastPlayTime > 0 && (System.currentTimeMillis() - lastPlayTime) < lastCoolTime) {
            return;
        }
        lastCoolTime = spaceTime;
        lastPlayTime = System.currentTimeMillis();
        float vol = (float) volume / 10;
        if (vol <= 0) vol = 1f;
        float finalVol = vol;
        getSoundPool().setOnLoadCompleteListener((soundPool, sampleId, status) -> {
            soundPool.play(sampleId, finalVol, finalVol, 0, 0, 1);
        });
        getSoundPool().load(mContext, rawId, 1);
    }


    public static void playSound(Context mContext, int rawId, int spaceTime) {
        playSound(mContext, rawId, 10, spaceTime);
    }

    public static void playSound(Context mContext, int rawId) {
        playSound(mContext, rawId, DEF_COOL_TIME);
    }

    public static void release() {
        if (soundPool != null) {
            soundPool.release();
        }
    }

    public static void setVolumeToMax(Context mContext) {
        //获取系统的Audio管理者
        AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        //最大音量
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //当前音量
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (currentVolume < maxVolume) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
        }
    }
}
